from django.shortcuts import render, HttpResponse
import json
import random
from datetime import datetime
from django.http import JsonResponse
from app01 import models
# 免除csrf验证
from django.views.decorators.csrf import csrf_exempt
from app01.utils.bootstrap import BootStrapModelFrom
from app01.utils.pagination import Pagination


class OrderModerForm(BootStrapModelFrom):
    class Meta:
        model = models.Order
        fields = "__all__"
        exclude = ['oid', 'admin']


def order_list(request):
    """订单"""
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset, page_size=5)

    form = OrderModerForm()
    context = {
        'form': form,
        "queryset": page_object.page_queryset,  # 分完页的数据
        'page_string': page_object.html()  # 生成的页码
    }
    return render(request, 'order_list.html', context)


# 免除csrf验证
@csrf_exempt
def order_add(request):
    """新建订单（Ajax请求）"""
    form = OrderModerForm(data=request.POST)
    if form.is_valid():
        # 订单号：oid没有让用户输入 所以要后台创建
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        # admin 管理员名字
        # form.instance.admin_id = 当亲登录系统的id
        # request.session['info']['id']     # 到登录中的session中查看当前登录id
        form.instance.admin_id = request.session['info']['id']
        # 打印
        # print(form.instance.oid)
        # 检验正确保存到数据库
        form.save()
        # return HttpResponse(json.dumps({'status': True}))
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def order_delete(request):
    """删除订单"""
    # 获取前台ajax发来的id
    uid = request.GET.get('uid')
    # 根据id在数据库中删除
    exists = models.Order.objects.filter(id=uid).exists()  # 判断数据是否存在
    if not exists:
        return JsonResponse({"status": False, 'error': '删除失败, 数据不存在'})
    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def order_detail(request):
    """根据ID获取订单详细"""

    """
    第一种： 
        # 获取id
    uid = request.GET.get("uid")

    # 根据id查询出详细
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'error': '不可编辑'})

    # 从数据库中获取的是一个对象 row_object
    result = {
        "status": True,
        "data": {
            "title": row_object.title,
            "price": row_object.price,
            "status": row_object.status,
        }
    }
    return JsonResponse(result)
    """

    # 获取id
    uid = request.GET.get("uid")

    # 根据id查询出详细
    # values('title', 'price', 'status') 直接获取是字典对象下面就不用在封装
    row_dict = models.Order.objects.filter(id=uid).values('title', 'price', 'status').first()
    print(row_dict)
    if not row_dict:
        return JsonResponse({'status': False, 'error': '数据不存在，不可编辑'})

    # 从数据库中获取的是一个对象 row_object
    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)

# 免除csrf验证
@csrf_exempt
def order_edit(request):
    """编辑"""
    # 获取订单号
    uid = request.GET.get('uid')
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({'status': False, 'msg': "数据不存在"})

    # 正确后就进行表单校验
    form = OrderModerForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})
